#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api import urlfetch
from datetime import date
import re
from bs4 import BeautifulSoup

DCC_URL_PATTERN = 'http://www.dunedin.govt.nz/events/whats-on-in-dunedin?SQ_CALENDAR_VIEW=day&SQ_CALENDAR_DATE={0}'
R1_URL_PATTERN = 'http://r1.co.nz/printable.php?type=playtime'
DUNEDIN_MUSIC_URL_PATTERN = 'http://dunedinmusic.com/gigs.php?data[start]={0}&data[venue]=&data[artist]=&search=Search'
EVENT_FINDER_TODAY_URL_PATTERN = 'http://www.eventfinder.co.nz/concerts-gig-guide/events/dunedin/date'
EVENT_FINDER_TOMORROW_URL_PATTERN = 'http://www.eventfinder.co.nz/concerts-gig-guide/events/dunedin/tomorrow'

class MainHandler(webapp.RequestHandler):
    def get(self):
        self.response.out.write(date.today())
        self.showPageContent(self.showDcc, 'DCC')
        self.showPageContent(self.showR1, 'R1')
        self.showPageContent(self.showDunedinMusic, 'DunedinMusic')
        self.showPageContent(self.showEventFinder, 'EventFinder')

    def showPageContent(self, function, identifier):
        try:
            function()
        except Exception as exceptionInstance:
            self.response.out.write('<br/>Could not retrieve info from {0}. {1}'.format(identifier, exceptionInstance))
             

    def showEventFinder(self):
        result = urlfetch.fetch(url=EVENT_FINDER_TODAY_URL_PATTERN)
        soup = BeautifulSoup(result.content)
        contentWrapper = soup.find('div', id="contentWrapperInner")
        self.response.out.write('<br/>{0}'.format(contentWrapper))

        result = urlfetch.fetch(url=EVENT_FINDER_TOMORROW_URL_PATTERN)
        soup = BeautifulSoup(result.content)
        contentWrapper = soup.find('div', id="contentWrapperInner")
        self.response.out.write('<br/>{0}'.format(contentWrapper))

        
    def showDunedinMusic(self):
        result = urlfetch.fetch(url=DUNEDIN_MUSIC_URL_PATTERN.format(date.today()))
        # Chop off all of the content prior to the "main_body" div as some part of it is invalid.
        m = re.search(r"<div[^>]+id=\s*\"main_body\"\s*>.*", result.content, re.DOTALL)#\s?id="main_body"main_body
        # Replace it with a minimal representation so we can add it to the soup.
        soup = BeautifulSoup('<html><body><div><div>' + m.group(0))
        box_content = soup.find(attrs={'class': 'box_content'})
        box_content.div.extract()
        box_content.div.extract()
        box_content.div.extract()
        box_content.div.extract()
        self.response.out.write(str('<br/>{0}</br>'.format(box_content)))
        

    def showR1(self):
        result = urlfetch.fetch(url=R1_URL_PATTERN)
        soup = BeautifulSoup(result.content, from_encoding='iso-8859-1')
        soup.body.p.extract()
        soup.body.p.extract()
        soup.body.p.extract()
        self.response.out.write(unicode(soup.body))
        

    def showDcc(self):
        result = urlfetch.fetch(url=DCC_URL_PATTERN.format(date.today()))
        soup = BeautifulSoup(result.content)

        listDictionary = {}
        for eventInfo in soup.find_all(attrs={'class': 'event-info'}):
            info = DccEventInfo(eventInfo)
            
            if info.category in listDictionary:
                listDictionary[info.category].append(info)
            else:
                listDictionary[info.category] = [info]

        for category in sorted(listDictionary.iterkeys()):
            self.response.out.write('<h4>** {0} **</h4>\n'.format(category))
            for info in sorted(listDictionary[category]):
                self.response.out.write("{0}".format(info.heading))
                if info.subheading.string: self.response.out.write("<i>{0}</i><br/>".format(info.subheading.string))
                self.response.out.write("{0}<br/>".format(info.when))
                self.response.out.write("{0}\n".format(info.where))
            self.response.out.write('<hr/>')
        

class DccEventInfo():
    def __init__(self, htmlFragment):
        self.heading = htmlFragment.find('h3')
        self.subheading = htmlFragment.find('p')
        self.__details = self.subheading.next_sibling.next_sibling

        ## Example:
        ##<p><strong>Category:</strong> Notified road closures<br /><strong>When:</strong> 31st Jul 2010 8:00am - 30th Jun 2012 5:00pm <br /><strong>Where:</strong> Harrop Street, Dunedin</p>
        m = re.search(r"<strong>Category:</strong>(?P<category>.*)<br\s?/><strong>When:</strong>(?P<when>.*)<br\s?/><strong>Where:</strong>(?P<where>.*)", unicode(self.__details))#self.__details.contents)
        self.category = m.group('category')
        self.when = m.group('when')
        self.where = m.group('where')

def main():
    application = webapp.WSGIApplication([('/', MainHandler)],
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
